/*
 * Copyright © OpenAtom Foundation.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.generator.baseInfo;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.dom.*;

/**
 * @author liu_wei
 */
public class CompilationUnitInfo extends BaseGenerateInfo {

    private CompilationUnit unit;

    private String packageName;
    private List<String> imports;
    private List<AbstractTypeDeclaration> types;
    private String filePath;

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public String getPackageName() {
        return packageName;
    }

    public CompilationUnitInfo() {
        imports = new ArrayList<String>();
        types = new ArrayList<AbstractTypeDeclaration>();
    }

    public void createDirectory(String dirPath) {
        File file = new File(dirPath);
        file.mkdirs();
    }

    @Override
    public void generate() {
        buildUnit();
        String packPath = buildPath();
//        Map<String, IHelpBuilder> builderMap = wac.getBeansOfType(IHelpBuilder.class);
        createDirectory(packPath);

        for (AbstractTypeDeclaration type : types) {
            buildFile(packPath, type);
        }
    }

    private void buildUnit() {
        unit = ast.newCompilationUnit();

        PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
        packageDeclaration.setName(ast.newName(packageName));
        unit.setPackage(packageDeclaration);

        if (imports != null && imports.size() > 0) {
            for (String importStr :
                    imports) {
                ImportDeclaration importDecl = ast.newImportDeclaration();
                importDecl.setName(ast.newName(importStr));
                unit.imports().add(importDecl);
            }
        }


    }

    private String buildPath() {
        String[] dirs = packageName.split("\\.");
        StringBuilder path = new StringBuilder(filePath);
        for (String dir :
                dirs) {
            path.append("/").append(dir);
        }
        return path.toString();
    }

    private void buildFile(String packPath, AbstractTypeDeclaration typeDeclaration) {
        String className = typeDeclaration.getName().toString();

        String fileName = packPath + "/" + className + ".java";
        System.out.println(fileName);
        File f = new File(fileName);
        FileWriter fw;
        try {
            OutputStreamWriter out = new OutputStreamWriter(
                    new FileOutputStream(f), // true to append
                    "UTF-8"
            );

//            fw = new FileWriter(f);
            out.write(unit.getPackage().toString());

            List<ImportDeclaration> imports = unit.imports();
            for (int i = 0; i < imports.size(); i++) {
                ImportDeclaration im = imports.get(i);
                out.write(im.toString());
            }
            out.write(typeDeclaration.toString());

            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("生成失败");
        }
    }

    public void addImport(String importName) {
        if (!imports.contains(importName))
            imports.add(importName);
    }

    public void setImports(List<String> imports) {
        this.imports = imports;
    }

    public void addType(AbstractTypeDeclaration type) {
        types.add(type);
    }
}
